type single = {
    mode: string;
    path: string;
    sha: string;
    type: string;
    url: string;
};
type returnType = {
    sha: string;
    tree: single[];
    truncated: boolean;
    url: string;
};
const fetchData = (url: string) => fetch(url).then((res) => res.json());

const githubGetter = async () => {
    const tree: returnType = await fetchData(
        "https://api.github.com/repos/google/material-design-icons/git/trees/master"
    );
    const { sha } = tree.tree.find((i) => i.path === "src")!;
    return fetchData(
        `https://api.github.com/repos/google/material-design-icons/git/trees/${sha}`
    ).then((res: returnType) => {
        return res.tree
            .reduce((col, { path, sha }) => {
                return col.then(async (result) => {
                    const url = `https://api.github.com/repos/google/material-design-icons/git/trees/${sha}`;
                    const iconList: returnType = await fetchData(url);
                    const data = {
                        type: path,
                        url,
                        iconList: iconList.tree.map((i) => i.path),
                    };
                    result.push(data);
                    return result;
                });
            }, Promise.resolve([] as Result[]))
            .then((i) => i.filter((ii) => ii.iconList.length));
    });
};
export type Result = {
    type: string;
    url: string;
    iconList: string[];
};
export const getAllMessage = async (reset = false): Promise<Result[]> => {
    const cache = localStorage.getItem("google_icon_cache");
    if (reset || !cache) {
        const data = await githubGetter();
        localStorage.setItem("google_icon_cache", JSON.stringify(data));
        return data;
    } else {
        return JSON.parse(cache);
    }
};
